﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Linq;

namespace TARADesktopDoctor
{
	public partial class CreatePatient
	{
        tara_wcf.ItaraServiceClient svc = new tara_wcf.ItaraServiceClient();

        int doctorID;
        public CreatePatient(int docID)
		{
			this.InitializeComponent();
            doctorID = docID;
            lblUsername.Text = LoginPage.doc.FirstName + " " + LoginPage.doc.LastName;
			// Insert code required on object creation below this point.

            
		}

        string imgName = "";
        bool fillFile = false;
        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            #region gender
            bool fillGender = false;
            string gender = "";
            if (rbtnMale.IsChecked == true)
            {
                gender = "Male";
                fillGender = true;
            }
            else if (rbtnFemale.IsChecked == true)
            {
                gender = "Female";
                fillGender = true;
            }
            //else
            //{
            //    //prompt user to select a gender
            //    MessageBox.Show("Fill in the mandatory fields.");
            //}
            #endregion

            #region email
            bool fillEmail = false;
            if (tbxEmail.Text != "")
            {
                if (tbxEmail.Text.Length < 50)
                {
                    if (IsValidEmail(tbxEmail.Text))
                    {
                        fillEmail = true;
                    }
                    //else
                    //{
                    //    tbxEmail.Text = "";
                    //    MessageBox.Show("Enter a valid email address.");
                    //}
                }
            }
            #endregion

            bool fillFirstName = false;
            if (tbxFirstName.Text != "")
            {
                if (tbxFirstName.Text.Length < 20)
                {
                    fillFirstName = true;
                }
            }

            bool fillLastName = false;
            if (tbxLastName.Text != "")
            {
                if (tbxLastName.Text.Length < 49)
                {
                    fillLastName = true;
                }
            }

            //bool fillCountry = false;
            //if (cbxCountry.SelectedValue != null)
            //{
            //    fillCountry = true;
            //}
            //else
            //{
            //    MessageBox.Show("Please select a country");
            //}

            bool fillAddress = false;
            if (tbxAddress1.Text != "")
            {
                if (tbxAddress1.Text.Length < 49)
                {
                    fillAddress = true;
                }
            }

            #region Postal Code, TelNum, MobNum --> checkNum
            double Num;
            bool fillPostalCode = false;
            if (double.TryParse(tbxPostalCode.Text, out Num))
            {
                if (tbxPostalCode.Text.Length == 6)
                {
                    fillPostalCode = true;
                }
                //else
                //{
                //    MessageBox.Show("Please enter a 6 digit Postal Code.");
                //}
            }

            bool fillTelNum = false;

            if (double.TryParse(tbxTelNum.Text, out Num))
            {
                if (tbxTelNum.Text.Length == 8)
                {
                    fillTelNum = true;
                }
                //else
                //{
                //    MessageBox.Show("Please enter a 8 digit Tel No.");
                //}
            }

            bool fillMobNum = false;
            if (double.TryParse(tbxMobNum.Text, out Num))
            {
                if (tbxMobNum.Text.Length == 8)
                {
                    fillMobNum = true;
                }
                //else
                //{
                //    MessageBox.Show("Please enter a 8 digit Mobile No.");
                //}
            }
            #endregion

            bool fillID = false;
            if (tbxIDNum.Text != "")
            {
                if (tbxIDNum.Text.Length == 9)
                {
                    if (NRICValidation(tbxIDNum.Text))
                    {
                        fillID = true;
                    }
                    else
                    {
                        //Invalid NRIC format
                    }
                }
                else
                {
                    //Invalid Length of NRIC
                }
            }

            #region date
            bool fillDOB = false;
            DateTime selectedDOB = Convert.ToDateTime(dtpBirthDate.SelectedDate);
            int result = DateTime.Compare(selectedDOB, DateTime.Now);
            if (result < 0)
            {
                fillDOB = true;
            }
            //else if (result > 0)
            //{
            //    MessageBox.Show("Date of Birth cannot be later than today.");
            //}

            bool fillAdminDate = false;
            DateTime selectedAdminDate = Convert.ToDateTime(dtpAdmissionDate.SelectedDate);
            int result2 = DateTime.Compare(selectedAdminDate, DateTime.Now);
            if (result < 0)
            {
                fillAdminDate = true;
            }
            #endregion

            if (fillAddress == true && fillDOB == true && fillAdminDate == true && fillEmail == true && fillFile == true && fillFirstName == true && fillGender == true && fillID == true && fillLastName == true && fillMobNum == true && fillPostalCode == true && fillTelNum == true)
            {
                try
                {
                    int add = svc.addNewPatient(tbxLastName.Text, tbxFirstName.Text, Convert.ToDateTime(dtpBirthDate.SelectedDate), gender, tbxAddress1.Text, tbxPostalCode.Text, tbxTelNum.Text, tbxMobNum.Text, tbxEmail.Text, doctorID, imgName, tbxIDNum.Text, Convert.ToDateTime(dtpAdmissionDate.SelectedDate));
                    if (add != 0)
                    {
                        tbxAddress1.Text = "";
                        tbxEmail.Text = "sample@hotmail.com";
                        tbxFirstName.Text = "";
                        tbxIDNum.Text = "Example S9234452E";
                        tbxLastName.Text = "";
                        tbxMobNum.Text = "8 Digit Singapore Number";
                        tbxPostalCode.Text = "6 Digit Postal Code";
                        tbxTelNum.Text = "8 Digit Singapore Number";
                        dtpAdmissionDate.Text = "";
                        dtpBirthDate.Text = "";
                        rbtnFemale.IsChecked = false;
                        rbtnMale.IsChecked = false;
                        imgProfilePicture.Source = null;
                        //Add patient to patientList
                        PatientSelectionPage.patientList.Add(svc.retrievePatient(add));
                        PatientSelectionPage.editted = true;
                        MessageBox.Show("Patient added sucessfully.");
                        //MainWindow rootWindow = Application.Current.MainWindow as MainWindow;
                        //PatientSelectionPage page = new PatientSelectionPage();
                        //rootWindow.frame1.Navigate(page);
                    }
                    else
                    {
                        MessageBox.Show("Adding patient unsucessfully.");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Image is too big.");
                }
            }
            else
            {
                MessageBox.Show("Please fill in the respectively field with valid input.");
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        #region browse upload and convert image to byte

        string fileName;
        long fileSize;
        byte[] imageByte;
        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            // Configure open file dialog box
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "Image"; // Default file name
            dlg.DefaultExt = ".png"; // Default file extension
            dlg.Filter = "Image (.png)|*.png"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();
            
            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                fileName = dlg.FileName;
                
                FileInfo f = new FileInfo(fileName);
                fileSize = f.Length;

                imgProfilePicture.Source = new BitmapImage(new Uri(@fileName));
                imageByte = ReadImageFile(fileName);
                imgName = upload(imageByte);
            }
        }

        private byte[] ReadImageFile(string PostedFileName)
        {
            try
            {
                FileStream fs = new FileStream(PostedFileName, FileMode.Open, FileAccess.Read);

                BinaryReader br = new BinaryReader(fs);

                byte[] image = br.ReadBytes((int)fs.Length);

                br.Close();

                fs.Close();

                return image;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

        private bool IsValidEmail(string strIn)
        {
            // Return true if strIn is in valid e-mail format.
            return Regex.IsMatch(strIn,
                   @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
                   @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
        }

        private bool NRICValidation(string nric)
        {
            nric = nric.ToUpper();
            int first = nric[0];
            int second = nric[1];
            int third = nric[2];
            int fourth = nric[3];
            int fifth = nric[4];
            int sixth = nric[5];
            int seventh = nric[6];
            int eighth = nric[7];
            int nineth = nric[8];

            int sum = Convert.ToInt16(second - '0') * 2 + Convert.ToInt16(third - '0') * 7 + Convert.ToInt16(fourth - '0') * 6 + Convert.ToInt16(fifth - '0') * 5 + Convert.ToInt16(sixth - '0') * 4 + Convert.ToInt16(seventh - '0') * 3 + Convert.ToInt16(eighth - '0') * 2;
            int reminder = sum % 11;
            if (first.Equals('S') || first.Equals('T'))
            {
                switch (reminder)
                {
                    case 0:
                        if (nineth.Equals('J'))
                        {
                            return true;
                        }
                        break;
                    case 1:
                        if (nineth.Equals('Z'))
                        {
                            return true;
                        }
                        break;
                    case 2:
                        if (nineth.Equals('I'))
                        {
                            return true;
                        }
                        break;
                    case 3:
                        if (nineth.Equals('H'))
                        {
                            return true;
                        }
                        break;
                    case 4:
                        if (nineth.Equals('G'))
                        {
                            return true;
                        }
                        break;
                    case 5:
                        if (nineth.Equals('F'))
                        {
                            return true;
                        }
                        break;
                    case 6:
                        if (nineth.Equals('E'))
                        {
                            return true;
                        }
                        break;
                    case 7:
                        if (nineth.Equals('D'))
                        {
                            return true;
                        }
                        break;
                    case 8:
                        if (nineth.Equals('C'))
                        {
                            return true;
                        }
                        break;
                    case 9:
                        if (nineth.Equals('B'))
                        {
                            return true;
                        }
                        break;
                    case 10:
                        if (nineth.Equals('A'))
                        {
                            return true;
                        }
                        break;
                }
            }
            else if (first.Equals('F') || first.Equals('G'))
            {
                sum += 4;
                reminder = sum % 11;
                switch (reminder)
                {
                    case 0:
                        if (nineth.Equals('X'))
                        {
                            return true;
                        }
                        break;
                    case 1:
                        if (nineth.Equals('W'))
                        {
                            return true;
                        }
                        break;
                    case 2:
                        if (nineth.Equals('U'))
                        {
                            return true;
                        }
                        break;
                    case 3:
                        if (nineth.Equals('T'))
                        {
                            return true;
                        }
                        break;
                    case 4:
                        if (nineth.Equals('R'))
                        {
                            return true;
                        }
                        break;
                    case 5:
                        if (nineth.Equals('Q'))
                        {
                            return true;
                        }
                        break;
                    case 6:
                        if (nineth.Equals('P'))
                        {
                            return true;
                        }
                        break;
                    case 7:
                        if (nineth.Equals('N'))
                        {
                            return true;
                        }
                        break;
                    case 8:
                        if (nineth.Equals('M'))
                        {
                            return true;
                        }
                        break;
                    case 9:
                        if (nineth.Equals('L'))
                        {
                            return true;
                        }
                        break;
                    case 10:
                        if (nineth.Equals('K'))
                        {
                            return true;
                        }
                        break;
                }
            }
            return false;
        }

        private void btnLogout_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MainPage.assignedList.Clear();
            MainPage.exeList.Clear();
            MainPage.gpList.Clear();
            MainPage.jointList.Clear();
            MainPage.patientDetail = null;
            MainPage.patientID = 0;
            //MainPage.selectedJoint = 0;
            LoginPage.doc = null;
            PatientSelectionPage.editted = false;
            NavigationService.Navigate(new LoginPage());
        }

        #region focus
        private void tbxTelNum_LostFocus(object sender, RoutedEventArgs e)
        {
            if (tbxTelNum.Text.Trim().ToString() == "")
            {
                tbxTelNum.Text = "8 Digit Singapore Number";
            }
        }

        private void tbxTelNum_GotFocus(object sender, RoutedEventArgs e)
        {
            if (tbxTelNum.Text.Trim().ToString() == "8 Digit Singapore Number")
            {
                tbxTelNum.Text = "";
            }
        }

        private void tbxMobNum_GotFocus(object sender, RoutedEventArgs e)
        {
            if (tbxMobNum.Text.Trim().ToString() == "8 Digit Singapore Number")
            {
                tbxMobNum.Text = "";
            }
        }

        private void tbxMobNum_LostFocus(object sender, RoutedEventArgs e)
        {
            if (tbxMobNum.Text.Trim().ToString() == "")
            {
                tbxMobNum.Text = "8 Digit Singapore Number";
            }
        }

        private void tbxEmail_LostFocus(object sender, RoutedEventArgs e)
        {
            if (tbxEmail.Text.Trim().ToString() == "")
            {
                tbxEmail.Text = "sample@hotmail.com";
            }
        }

        private void tbxEmail_GotFocus(object sender, RoutedEventArgs e)
        {
            if (tbxEmail.Text.Trim().ToString() == "sample@hotmail.com")
            {
                tbxEmail.Text = "";
            }
        }

        private void tbxIDNum_LostFocus(object sender, RoutedEventArgs e)
        {
            if (tbxIDNum.Text.Trim().ToString() == "")
            {
                tbxIDNum.Text = "Example S9234452E";
            }
        }

        private void tbxIDNum_GotFocus(object sender, RoutedEventArgs e)
        {
            if (tbxIDNum.Text.Trim().ToString() == "Example S9234452E")
            {
                tbxIDNum.Text = "";
            }
        }

        private void tbxPostalCode_GotFocus(object sender, RoutedEventArgs e)
        {
            if (tbxPostalCode.Text.Trim().ToString() == "6 Digit Postal Code")
            {
                tbxPostalCode.Text = "";
            }
        }

        private void tbxPostalCode_LostFocus(object sender, RoutedEventArgs e)
        {
            if (tbxPostalCode.Text.Trim().ToString() == "")
            {
                tbxPostalCode.Text = "6 Digit Postal Code";
            }
        }

        #endregion focus

        public string upload(byte[] fileBytes)
        {
            string fileName = System.IO.Path.GetRandomFileName();
            fileName = fileName.Replace(".", "");
            fileName += ".png";
            bool result = false;
            try
            {
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                });
                //CloudStorageAccount cloudStorageAccount = CloudStorageAccount
                // Get the storage account reference
                CloudStorageAccount objStorage = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=tarastorage;AccountKey=GOu+LJLRqTxq7P0ZH89oNGYJFYmLkvayfJwIbINXI8cyv+q079VKOg4FS1ZSZuZJk/eAq8K81t8k2KVJ3b71EQ==");
                // get the Client reference using storage blobend point
                CloudBlobClient objClient = new CloudBlobClient(objStorage.BlobEndpoint, objStorage.Credentials);
                // Get Container reference
                // If i set to face, i can't retrieve it T>T
                //CloudBlobContainer objContainer = objClient.GetContainerReference("face");
                CloudBlobContainer objContainer = objClient.GetContainerReference("tarastorage");
                // Get blob reference
                CloudBlob obj = objContainer.GetBlobReference(fileName);
                // Set meta values
                obj.Metadata["MetaName"] = "meta";
                // Open a stream using the cloud object
                BlobStream blobstream = obj.OpenWrite();
                // Write the stream to the blob database
                blobstream.Write(imageByte, 0, imageByte.Count());
                blobstream.Close();
                result = true;
                fillFile = true;
            }
            catch (Exception)
            {
                result = false;
            }
            return result == true ? "http://tarastorage.blob.core.windows.net/tarastorage/" + fileName : String.Empty;
        }
    }
}